package servlet;

import bean.Customer;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("list")
public class ListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.编写查询的sql语句
        String sql = "select * from customer c ,room r where c.cid=r.id";
        //2.调用工具类，执行sql，得到结果集
        ResultSet rs = DBUtil.query(sql);
        //3.把结果集变成一个集合
        ArrayList<Customer> list = new ArrayList<>();
        //3.5遍历结果集，将元素封装成对象，添加到list集合
        try {
            while (rs.next()){
                int cid = rs.getInt(1);
                String name = rs.getString(2);
                String type = rs.getString(4);
                Customer customer = new Customer(cid, name, type);
                list.add(customer);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //将集合放入request域中
     req.setAttribute("list",list);
        //5.把请求转发给jsp
        req.getRequestDispatcher("/WEB-INF/List.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}